<template>
    <div class="funding-item-template">
        <div class="grid-content bg-purple funding-item-container" @click="gotoDetail">
            <a>
                <div class="image-area" :style="getBGImage(fundingItem.campaignImage)"></div>
                <div class="seperator"></div>
                <div class="main-content">
                    <p class="title">{{fundingItem.title}}</p>
                    <p class="desc">{{fundingItem.tagline}}</p>
                    <p class="category">{{fundingItem.category}}</p>
                    <div class="funding-detail">
                        <span>{{fundingItem.priceType}} ${{fundingItem.price}}</span>
                        To Be Raised
                    </div>
                    <div class="progress">
                        <div class="el-progress">
                            <el-progress :percentage="percentage > 100 ? 100 : percentage" :show-text="false" :stroke-width="16"></el-progress>
                        </div>
                        <div class="el-progress-text">
                            {{percentage}} %
                        </div>
                    </div>
                    <div class="detail" v-if="new Date() < new Date(fundingItem.campaignDuration)">
                        <i class="el-icon-time"></i>{{fundingItem.campaignDuration | dateFormat}}
                    </div>
                    <div v-else> 0 days left</div>
                </div>
                <div class="ope-area" v-if="backShow">
                    <el-button size="small" type="primary" @click.stop="backHandler" class="custom-button">Back It</el-button>
                    <el-button size="small" type="danger" @click.stop="removeHandler">Remove It</el-button>
                </div>
            </a>
        </div>

        <el-dialog
                title="Back This Project"
                :visible.sync="peakDialogVisible"
                width="30%"
                center>
            <div class="project-peak-area">
               <!-- <el-row>
                    <el-card :body-style="{ padding: '16px' }" shadow="hover" class="price-area">
                        <div>
                            <el-input placeholder="" v-model="singlePrice" class="input-with-select">
                                <template slot="prepend">$</template>
                                <span slot="append">USD</span>
                            </el-input>
                        </div>
                        <div class="ope-area">
                            <el-button type="primary" class="submit-button"
                                       @click="confirmHandler(999999, singlePrice)">Confirm
                            </el-button>
                        </div>
                    </el-card>
                </el-row>-->
                <el-row v-for="item in peaksList"
                        :key="item.id"
                        class="single-item">
                    <el-col>
                        <el-card :body-style="{ padding: '16px' }" shadow="hover">
                            <!--<img src="~assets/film.png" class="image">-->
                            <div class="image-area" v-if="item.peakImage" :style="getPeakBGImage(item.peakImage)">
                            </div>
                            <div class="peak-product">
                                <span>{{item.title}}</span>
                            </div>
                            <div class="peak-price">
                                <span class="price">${{item.price}}</span>
                                <span class="perk_currency">USD</span>
                                <span class="content"></span>
                            </div>

                            <div class="peak-date">
                            <span class="title">
                                {{item.description}}
                            </span>
                                <span class="content items" v-if="item.peakItems">
                                Included Items
                            </span>
                                <ul v-if="item.peakItems">
                                    <li v-for="text in item.peakItems"
                                        :key="item"
                                        class="single-item">
                                        {{text}}
                                    </li>
                                </ul>
                                <p style="font-weight: bold; margin-top: 16px;">Estimated Shipping</p>
                                <span class="date">
                                {{item.duration | dateFormat}}
                            </span>
                                <!-- <span class="date">
                                 {{item.duration | dateFormat}}
                             </span>-->
                            </div>

                            <!--<div class="peak-people">
                                <b>{{item.peakNum}}</b>
                                claimed
                            </div>-->
                            <div class="action-area">
                                <el-button type="primary" class="submit-button"
                                           @click="confirmHandler(item.id, item.price)">GET THIS PERK
                                </el-button>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>


        <el-dialog title="We’d like to hear your feedback…" :visible.sync="feedbackFormVisible" class="tip-form">
            <el-form>
                <el-form-item>
                    <span class="tip">Please tell us your thoughts about the benefits and potential risk of investing in campaigns in our platform!</span>
                    <el-input type="textarea" v-model="suggestion" :rows="4"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="feedbackFormVisible = false">Cancel</el-button>
                <el-button type="primary" @click="feedbackSubmitHandler">Submit</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import moment from 'moment'
    import {mapState, mapMutations} from 'vuex'
    import {apiQueryPeakByCID} from '@/api/peak'
    import {apiSaveUserPeak} from '@/api/user_peak'
    import {saveFeedback} from '@/api/feedback'
    import {removeBookmarkByCID} from '@/api/bookmark'
    import {saveUserLog} from '@/api/log'
    import {getVersion} from '@/utils/auth'


    export default {
        data() {
            return {
                peakDialogVisible: false,
                peaksList: [],
                singlePrice: 100,
                feedbackFormVisible: false,
                peakId: 0,
                price: 0,
                suggestion: "",
            }
        },
        props: {
            fundingItem: {
                required: true
            },
            backShow: {
                default: false
            }
        },
        computed: {
            ...mapState({
                'userId': state => state.user.userId,
            }),
            percentage() {
                var percentage = parseFloat(((this.fundingItem.totalPrice / this.fundingItem.price) * 100).toFixed(2))
                console.log(percentage)
                // return percentage > 100 ? 100 : percentage;
                return  percentage;
            }

        },
        methods: {
            async feedbackSubmitHandler() {

                var that = this

                var queryData = {
                    userId: this.userId,
                    campaignId: this.fundingItem.id,
                    peakId: this.peakId,
                    price: this.price,
                    content: this.suggestion
                }

                // const saveRes = await saveFeedback(queryData)

                // const result = await apiSaveUserPeak(queryData)

                /*if (0 === result.code) {
                    // 如果查询成功
                    that.$message({
                        type: 'success',
                        message: 'success!'
                    });
                    setTimeout(function () {
                        that.feedbackFormVisible = false
                    }, 1000)
                }*/

                window.version = getVersion()
                window.userId = this.userId;

                // this.$alert('Thank you for completing the investment task! Please click on the below link to tell us about your experience ' +
                //     'on the platform: <a href="javascript:void(0);" target="_blank" style="text-decoration: underline; font-weight: bold" onclick="openFeedbackLink()"> click here to start </a>', 'Notice', {
                //     confirmButtonText: 'Confirm',
                //     dangerouslyUseHTMLString: true
                // })

                openFeedbackLink()


                // 实验阶段暂时不保存
                that.$message({
                    type: 'success',
                    message: 'success!'
                });
                setTimeout(function () {
                    that.feedbackFormVisible = false
                }, 1000)


            },
            confirmHandler(peakId, price) {
                var that = this

                this.$confirm('Are you sure you want to invest in this perk?', 'Notice', {
                    confirmButtonText: 'Confirm my decision and continue to questionnaire',
                    cancelButtonText: 'I am not ready. Back to the platform and continue browsing campaigns',
                    showClose: false,
                    closeOnClickModal: false,
                    // closeOnPressEscape: false,
                    customClass: 'my-custom-dialog',
                    cancelButtonClass: 'my-cancel-button',
                    confirmButtonClass: 'my-confirm-button',
                    type: 'warning'
                }).then(() => {


                    var tip = {
                        operation: "Click confirm from perk",
                        params: JSON.stringify({
                            "userId": this.userId,
                            "peakId": peakId,
                            "operation": "Click confirm from perk"

                        })
                    }

                    saveUserLog(tip);



                    this.doPeak(peakId, price)



                }).catch(err => {


                    var tip = {
                        operation: "Click not ready from perk",
                        params: JSON.stringify({
                            "userId": this.userId,
                            "peakId": peakId,
                            "operation": "Click not ready from perk"
                        })
                    }

                    saveUserLog(tip);



                })


            },

            doPeak(peakId, price) {

                var that = this

                if (999999 == peakId) {

                    var tip = {
                        operation: "Enter donation amount",
                        params: JSON.stringify({
                            "userId": this.userId,
                            "campaignId": this.fundingItem.id,
                            "peakId": peakId
                        })
                    }
                } else {

                    var tip = {
                        operation: "Get this perk",
                        params: JSON.stringify({
                            "userId": this.userId,
                            "campaignId": this.fundingItem.id,
                            "peakId": peakId
                        })
                    }
                }


                saveUserLog(tip);

                that.peakId = peakId
                that.price = price
                // that.feedbackFormVisible = true
                that.feedbackSubmitHandler()
            },

            getPeakBGImage(image) {

                // var imagePath = Constants.ICON_HOST + this.userId
                var imagePath = image

                return `background-image: url('${imagePath}');background-size: 100% 100%;
                background-repeat: no-repeat;`

            },
            getBGImage(image) {
                return "background-image: url('" + image + "');"
            },
            gotoDetail() {
                var that = this
                if (this.backShow) {
                    var tip = {
                        operation: "Enter campaign page from bookmark page",
                        params: JSON.stringify({"userId": this.userId, "campaignId": this.fundingItem.id})

                    }
                } else {
                    var tip = {
                        operation: "Enter campaign page from campaign list",
                        params: JSON.stringify({"userId": this.userId, "campaignId": this.fundingItem.id})

                    }
                }

                saveUserLog(tip);


                this.$router.push({
                    path: "/projectDetail", query: {
                        campaignId: this.fundingItem.id
                    }
                })
            },
            async removeHandler(e) {
                e.preventDefault()

                var tip = {
                    operation: "Remove bookmark",
                    params: JSON.stringify({"userId": this.userId, "campaignId": this.fundingItem.id})

                }

                saveUserLog(tip);

                const res = await removeBookmarkByCID(this.fundingItem.bookmarkId)

                if (0 == res.code) {
                    this.$emit('myEvent', this.fundingItem.bookmarkId)
                }


            },
            async backHandler(e) {
                e.preventDefault()

                var tip = {
                    operation: "Back it",
                    params: JSON.stringify({"userId": this.userId, "campaignId": this.fundingItem.id})
                }

                saveUserLog(tip);

                const res = await apiQueryPeakByCID(this.fundingItem.id)

                if (0 === res.code) {
                    // 如果查询成功
                    console.log(res)
                    this.peaksList = res.data.records
                    // vm.campaign.tag = res.campaign.tag.split(",")
                }

                this.peakDialogVisible = true
            },
        },
        filters: {
            dateFormat(time) {
                // return moment().to(moment(time))
                // return moment(time).format('MMMM Do YYYY')
                return moment(time).fromNow()
            }
        },
    }
</script>

<style lang="scss">

    .my-custom-dialog {
        .el-message-box__btns {
            display: flex;
            button {
                padding: 0px;
            }
            span {
                word-break:break-all;
                width:auto;
                display:block;
                white-space:normal;
                word-wrap: break-word ;
                overflow: hidden ;
                font-size: 15px;
                /*line-height: 18px;*/
            }
        }
        .my-cancel-button {
            height: 60px;
            width: 200px;
        }

        .my-confirm-button {
            height: 60px;
            width: 200px;
        }
    }



    .funding-item-template {
        border-radius: 2px;
        transition: all 150ms linear;
        cursor: pointer;
        margin-bottom: 36px;
        padding-bottom: 26px;
        height: 526px;
        padding: 0 15px;




        .funding-item-container {
            border: 1px solid #dddddd;
            .image-area {
                width: 100%;
                height: 273px;
                background-repeat: no-repeat;
                background-size: 100% 100%;
                background-position: top center;
            }
            .seperator {
                color: #dddddd;
                width: 90%;
                height: 1px;
                margin-left: 5%;
            }
            .main-content {
                text-align: left;
                padding: 6px;
                .title {
                    font-family: "Benton Sans Medium";
                    font-size: 16px;
                    font-weight: normal;
                    line-height: 26px;
                    letter-spacing: 0;
                    width: inherit;
                    height: 53px;
                }
                .category {
                    font-family: "benton-sans", "Helvetica", "sans-serif";
                    font-size: 13px;
                    font-weight: normal;
                    line-height: 26px;
                    letter-spacing: 1px;
                    width: inherit;
                    color: #6A6A75;
                    text-transform: uppercase;
                }
                .desc {
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-size: 13px;
                    font-weight: normal;
                    line-height: 19px;
                    padding-top: 5px;
                    padding-bottom: 5px;
                    height: 67px;
                    color: #6a6a6a;
                }
                .type {
                    color: #6a6a6a;
                    margin-bottom: 6px;
                }
                .progress {
                    margin: 6px 0;
                    display: flex;
                    .el-progress {
                        width: 82%;
                    }
                    .el-progress-text {
                        margin-left: -26px;
                    }
                }
                .detail {
                    margin-bottom: 2px;
                    .el-icon-time {
                        margin-right: 6px;
                    }
                }
                .funding-detail {
                    span {
                        font-family: "benton-sans", "Helvetica", "sans-serif";
                        font-weight: 700;
                        font-size: 14px;
                        line-height: 20px;
                        color: #2a2a2a;
                    }
                }
            }
            .ope-area {
                text-align: center;
                margin-bottom: 16px;
                .custom-button {
                    background-color: #069000;
                }
            }
        }
        .project-peak-area {
            .single-item {
                padding-bottom: 16px;
            }
            .price-area {
                .el-card__body {
                    display: flex;
                    .ope-area {
                        margin-left: 6px;
                    }
                }
            }
            .image-area {
                width: 100%;
                height: 160px;
            }
            .peak-price {
                .price {
                    padding-right: 5px;
                    margin-bottom: 5px;
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-size: 20px;
                    font-weight: bold;
                    line-height: 26px;
                }
                .perk_currency {
                    color: #6a6a6a;
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-size: 14px;
                    font-weight: normal;
                    line-height: 20px;
                }
                .content {
                    color: #6a6a6a;
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-size: 14px;
                    font-weight: normal;
                    line-height: 20px;
                }
            }
            .peak-product {
                font-family: "Benton Sans Medium";
                font-size: 18px;
                font-weight: normal;
                line-height: 28px;
                letter-spacing: 0;
            }
            .peak-date {
                span {
                    display: block;
                }
                .title {
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-size: 14px;
                    line-height: 20px;
                }
                .content {
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-weight: bold;
                    font-size: 14px;
                    line-height: 20px;
                }
                .date {
                    font-family: "Benton Sans", "Helvetica", "sans-serif";
                    font-size: 14px;
                    font-weight: normal;
                    line-height: 20px;
                }
                .single-item {
                    list-style-type: disc;
                    margin-left: 26px;
                }
                .items {
                    margin-top: 16px;
                }
            }
            .peak-people {
                font-size: 14px;
                color: #6a6a6a;
                margin-top: 10px;
            }
            .action-area {
                padding: 6px;
                text-align: center;
                color: #e51075 !important;
                span {
                    text-transform: uppercase;
                }
                .submit-button {
                    width: 100%;
                    margin: 16px 0px;
                    background-color: transparent !important;
                    span {
                        color: #e51075 !important;
                    }
                }
            }

        }
    }
</style>
